import openai
import os

# API 配置
api_key = "sk-ThA0WI5NVgQ1xYUf8BriyRJfIqBWRvbV5rrzmAWBvdjxsnWP"
base_url = "https://yibuapi.com/v1"


def read_file_content(file_path):
    """读取指定路径的文件内容"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except Exception as e:
        return f"文件读取失败: {str(e)}"


def get_openai_response(file_content, question, api_key, base_url):
    """基于文件内容和问题向OpenAI发送请求"""
    try:
        full_prompt = f"根据以下文本内容回答问题：\n\n{file_content}\n\n问题：{question}"
        client = openai.OpenAI(api_key=api_key, base_url=base_url)
        response = client.chat.completions.create(
            model="gpt-4-turbo",
            messages=[{"role": "user", "content": full_prompt}]
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"请求失败: {str(e)}"


if __name__ == "__main__":
    # 手动指定桌面路径（替换为实际路径）
    # 示例：若桌面在D盘，路径为 r"D:\Users\你的用户名\Desktop"
    desktop_path = r"D:\桌面\竞赛\挑战杯+人工智能"
    file_path = os.path.join(desktop_path, "第3章 数据获取.docx")

    # 读取文件内容
    file_content = read_file_content(file_path)
    if "文件读取失败" in file_content:
        print(file_content)
    else:
        print(f"成功读取文件，内容长度: {len(file_content)} 字符")

        # 自定义问题
        user_question = "假如你是一个智能考试机器人，请你根据知识库总结出一道主观性题目来考察我"

        # 发送请求
        response = get_openai_response(file_content, user_question, api_key, base_url)
        print(f"\n问题: {user_question}")
        print(f"回答: {response}")